package com.demo.redis.utils;

import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * @author peter
 * @date 2022/2/15 14:00
 */
public class PrefixRedisSerializer implements RedisSerializer<String> {

    private final Charset charset;
    public static final StringRedisSerializer US_ASCII;
    public static final StringRedisSerializer ISO_8859_1;
    public static final StringRedisSerializer UTF_8;

    public String prefix = "defalut";

    public PrefixRedisSerializer() {
        this(StandardCharsets.UTF_8, "");
    }

    public PrefixRedisSerializer(Charset charset, String prefix) {
        Assert.notNull(charset, "Charset must not be null!");
        this.charset = charset;
        this.prefix = prefix;
    }

    public String deserialize(@Nullable byte[] bytes) {
        if (bytes == null) {
            return null;
        }

        String key = new String(bytes, this.charset);

        if (! StringUtils.isEmpty(this.prefix)) {
            key = this.prefix + ":" + key;
        }

        return key;
    }


    public byte[] serialize(@Nullable String string) {
        if (string == null) {
            return null;
        }

        if (! StringUtils.isEmpty(this.prefix)) {
            string = this.prefix + ":" + string;
        }

        return string.getBytes(this.charset);
    }

    public Class<?> getTargetType() {
        return String.class;
    }

    static {
        US_ASCII = new StringRedisSerializer(StandardCharsets.US_ASCII);
        ISO_8859_1 = new StringRedisSerializer(StandardCharsets.ISO_8859_1);
        UTF_8 = new StringRedisSerializer(StandardCharsets.UTF_8);
    }
}
